package com.dinggou.shopjb.adapters;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;


import com.dinggou.shopjb.R;
import com.dinggou.shopjb.base.BaseRVAdapter;
import com.dinggou.shopjb.base.BaseRVHolder;
import com.dinggou.shopjb.base.BaseViewHolder;
import com.dinggou.shopjb.bean.OrderInfoBean;
import com.dinggou.shopjb.bean.OrderInfoGroupBean;
import com.dinggou.shopjb.utils.GlideUtils;
import com.dinggou.shopjb.utils.LogUtil;
import com.dinggou.shopjb.view.CustomTextView;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class OrderRVAdapter extends BaseRVAdapter<OrderInfoGroupBean> {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm:ss", Locale.CHINA);
    private SparseArray<int[]> posArray;

    public OrderRVAdapter(Context context, List<OrderInfoGroupBean> list) {
        super(context, list);
        posArray = new SparseArray<>();
    }

    @Override
    public int onCreateViewLayoutID(int viewType) {
        return R.layout.item_order_layout;
    }


    @Override
    public int getItemViewType(int position) {
        return isGroup(position) ? 0 : 1;
    }


    @Override
    public BaseRVHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if (viewType == 0) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_order_title_layout, parent, false);
            return new TitleViewHolder(view);
        } else {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_order_layout, parent, false);
            return new OrderViewHolder(view);
        }
    }

    private class TitleViewHolder extends BaseRVHolder {

        private TitleViewHolder(View view) {
            super(view);
        }
    }

    private class OrderViewHolder extends BaseRVHolder {
        public double cacheProfitAndLoss;
        public int cacheTargetProfit;
        public int cacheStopLoss;
        private AnimationSet showAnimation = null;
        private AnimationSet hideAnimation = null;

        private OrderViewHolder(View view) {
            super(view);
            setPriceAnimtion(view.findViewById(R.id.view_bg));
        }

        private void startUpAnim(View view_bg) {
            view_bg.setBackgroundResource(R.drawable.border_new_home_anim_red);
            view_bg.startAnimation(showAnimation);
        }

        private void startDownAnim(View view_bg) {
            view_bg.setBackgroundResource(R.drawable.border_new_home_anim_green);
            view_bg.startAnimation(showAnimation);
        }

        private void setPriceAnimtion(View view_bg) {
            hideAnimation = new AnimationSet(true);
            hideAnimation.setDuration(300);
            AlphaAnimation alphadown = new AlphaAnimation(1, 0);
            alphadown.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view_bg.setBackgroundColor(Color.TRANSPARENT);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            hideAnimation.addAnimation(alphadown);

            showAnimation = new AnimationSet(true);
            showAnimation.setDuration(300);
            AlphaAnimation alpha = new AlphaAnimation(0, 1);
            alpha.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view_bg.startAnimation(hideAnimation);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            showAnimation.addAnimation(alpha);
        }

        private void clearAnim(View view_bg){
            Log.d("dangzt", "clearAnim: ");
            view_bg.setBackgroundColor(Color.TRANSPARENT);
            view_bg.clearAnimation();
        }
    }

    @Override
    public void onBindView(BaseRVHolder mHolder, final int position) {
        BaseViewHolder holder = mHolder.getViewHolder();
        if (mHolder instanceof TitleViewHolder) {
            RelativeLayout rl_group = holder.get(R.id.rl_group);
            TextView tv_group_pro_name = holder.get(R.id.tv_group_pro_name);
            TextView tv_group_price = holder.get(R.id.tv_group_price);
            TextView tv_group_rise_fall = holder.get(R.id.tv_group_rise_fall);

            final OrderInfoGroupBean mGroupBean = mList.get(getGroupPosition(position));
            tv_group_pro_name.setText(mGroupBean.getProName());
            if (mGroupBean.getRise() >= 0) {
                tv_group_price.setTextColor(ContextCompat.getColor(mContext, R.color.buy_red));
                tv_group_rise_fall.setTextColor(ContextCompat.getColor(mContext, R.color.buy_red));
                tv_group_rise_fall.setText(String.format("+%s   +%s",  FormatUtil.formatDouble2(mGroupBean.getRise()), mGroupBean.getRisePercent()));
                tv_group_rise_fall.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_home_market_up, 0);
            } else {
                tv_group_price.setTextColor(ContextCompat.getColor(mContext, R.color.buy_green));
                tv_group_rise_fall.setTextColor(ContextCompat.getColor(mContext, R.color.buy_green));
                tv_group_rise_fall.setText(String.format("%s   %s",  FormatUtil.formatDouble2(mGroupBean.getRise()), mGroupBean.getRisePercent()));
                tv_group_rise_fall.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_home_market_down, 0);
            }
            tv_group_price.setText(FormatUtil.formatDouble2(mGroupBean.getLatestPrice()));


            rl_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOrderListener.onClickOrderMarket(mGroupBean.getProCode());
                }
            });
        } else if (mHolder instanceof OrderViewHolder){
            ImageView iv_goods_img = holder.get(R.id.iv_goods_img);
            TextView tv_pro_name = holder.get(R.id.tv_pro_name);
            TextView tv_pro_number = holder.get(R.id.tv_pro_number);
            CustomTextView tv_float_profit_loss = holder.get(R.id.tv_float_profit_loss);
            ImageView iv_trade_type = holder.get(R.id.iv_trade_type);
            ImageView iv_money_type = holder.get(R.id.iv_money_type);
            TextView tv_create_price = holder.get(R.id.tv_create_price);
            TextView tv_poundage = holder.get(R.id.tv_poundage);
            TextView tv_target_loss_value = holder.get(R.id.tv_target_loss_value);
            TextView tv_unit_price = holder.get(R.id.tv_unit_price);
            ImageView iv_tips = holder.get(R.id.iv_tips);
            TextView tv_create_time = holder.get(R.id.tv_create_time);
            TextView tv_pick_goods = holder.get(R.id.tv_pick_goods);
            TextView tv_update = holder.get(R.id.tv_update);
            TextView bt_sell = holder.get(R.id.bt_sell);
            TextView tv_detail = holder.get(R.id.tv_detail);
            View view_bg = holder.get(R.id.view_bg);

            final OrderInfoBean mOrderInfoBean = getItemOrder(position);
            ((OrderViewHolder) mHolder).clearAnim(view_bg);
            LogUtil.d("dangzt", "波动" + mOrderInfoBean.profitAndLoss);
            if (((OrderViewHolder) mHolder).cacheProfitAndLoss == mOrderInfoBean.profitAndLoss
            && ((OrderViewHolder) mHolder).cacheStopLoss == mOrderInfoBean.stop_loss
            && ((OrderViewHolder) mHolder).cacheTargetProfit == mOrderInfoBean.target_profit) return;
            bt_sell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOrderListener.onClickSell(mOrderInfoBean);
                }
            });

            tv_pick_goods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOrderListener.onClickGetGoods(mOrderInfoBean);
                }
            });

            tv_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOrderListener.onClickChangeProfitLost(mOrderInfoBean);
                }
            });

            tv_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOrderListener.onClickDetail(mOrderInfoBean);
                }
            });

            int redColor = ContextCompat.getColor(mContext, R.color.buy_red);
            int greenColor = ContextCompat.getColor(mContext, R.color.buy_green);

            if (mOrderInfoBean.trade_type == 2) {
                iv_trade_type.setImageResource(R.drawable.img_home_up);
            } else {
                iv_trade_type.setImageResource(R.drawable.img_home_down);
            }

            GlideUtils.showImageRoundOptions(mContext, mOrderInfoBean.product_img, iv_goods_img, 12);
            String profitAndLoss = FormatUtil.formatMoney(mOrderInfoBean.profitAndLoss);
            String price = FormatUtil.formatDouble2(mOrderInfoBean.build_price);
            if (mOrderInfoBean.profitAndLoss >= 0) {
                tv_float_profit_loss.setTextColor(redColor);
            } else {
                tv_float_profit_loss.setTextColor(greenColor);
            }
            String poundage = "";
            if(mOrderInfoBean.use_ticket == 1){
                poundage = "0";
            }else{
                poundage = FormatUtil.formatDouble2(ArithUtil.mul(mOrderInfoBean.amount,mOrderInfoBean.unit_price));
            }
            String floatDot = FormatUtil.formatDouble2(ArithUtil.sub(mOrderInfoBean.new_price, mOrderInfoBean.build_price) * mOrderInfoBean.multiple);

            tv_float_profit_loss.setText(profitAndLoss);
            tv_create_price.setText(price);
            tv_poundage.setText(floatDot);
            tv_target_loss_value.setText( mOrderInfoBean.target_profit + "/" + mOrderInfoBean.stop_loss);
            tv_unit_price.setText(poundage);
            iv_money_type.setVisibility(mOrderInfoBean.use_ticket == 1 ? View.VISIBLE : View.GONE);
            tv_create_time.setText(dateFormat.format(new Date(Long.parseLong(mOrderInfoBean.build_time))));
            if (mOrderInfoBean.isFirst == 0) {
                //正常订单
                tv_pro_number.setVisibility(View.VISIBLE);
                iv_tips.setVisibility(View.GONE);

                tv_pro_name.setText(mOrderInfoBean.pro_name);
                tv_pro_number.setText(" x " + mOrderInfoBean.amount + "件");
            } else {
                //新手单
                tv_pro_number.setVisibility(View.GONE);
                iv_tips.setVisibility(View.VISIBLE);

                tv_pro_name.setText("新手券实时增益");
            }
            if (((OrderViewHolder) mHolder).cacheProfitAndLoss > 0 && ((OrderViewHolder) mHolder).cacheProfitAndLoss != mOrderInfoBean.profitAndLoss){
                if (mOrderInfoBean.profitAndLoss - ((OrderViewHolder) mHolder).cacheProfitAndLoss >= 0) {
                    ((OrderViewHolder) mHolder).startUpAnim(view_bg);
                }else {
                    ((OrderViewHolder) mHolder).startDownAnim(view_bg);
                }
            }
            ((OrderViewHolder) mHolder).cacheProfitAndLoss = mOrderInfoBean.profitAndLoss;
            ((OrderViewHolder) mHolder).cacheTargetProfit = mOrderInfoBean.target_profit;
            ((OrderViewHolder) mHolder).cacheStopLoss = mOrderInfoBean.stop_loss;
        }
    }

    @Override
    public boolean setData(List<OrderInfoGroupBean> data) {
        mList.clear();
        mList.addAll(data);
        calculatePosArray();
        notifyDataSetChanged();
        return true;
    }

    public void clear() {
        mList.clear();
        posArray.clear();
        notifyDataSetChanged();
    }

    private void calculatePosArray() {
        posArray.clear();
        int position = 0;
        for (int i = 0; i < mList.size(); i++) {
            posArray.put(position++, new int[]{i, -1});
            int childCount = mList.get(i).getChild().size();
            for (int j = 0; j < childCount; j++) {
                posArray.put(position++, new int[]{i, j});
            }
        }
    }

    @Override
    public int getItemCount() {
        return posArray.size();
    }

    public int getOrderNumber() {
        int number = 0;
        for (OrderInfoGroupBean bean : mList) {
            number = number + bean.getChild().size();
        }
        return number;
    }

    private OrderInfoBean getGroupItemOrder(int position) {
        return mList.get(getGroupPosition(position)).getChild().get(0);
    }

    private OrderInfoBean getItemOrder(int position) {
        return mList.get(getGroupPosition(position)).getChild().get(getItemPosition(position));
    }

    private int getItemPosition(int position) {
        return posArray.get(position)[1];
    }

    private int getGroupPosition(int position) {
        return posArray.get(position)[0];
    }

    private boolean isGroup(int position) {
        return posArray.get(position)[1] == -1;
    }

    public void remove(String orderId) {
        int groupIndex = 0;
        int childIndex = 0;
        boolean isContinue = true;
        for (int i = 0; i < mList.size(); i++) {
            List<OrderInfoBean> childList = mList.get(i).getChild();
            for (int j = 0; j < childList.size() && isContinue; j++) {
                if (orderId.equals(childList.get(j).order_id)) {
                    groupIndex = i;
                    childIndex = j;
                    isContinue = false;
                    break;
                }
            }
        }
        if (mList.get(groupIndex).getChild().size() == 1) {
            mList.remove(groupIndex);
        } else {
            mList.get(groupIndex).getChild().remove(childIndex);
        }
        calculatePosArray();
        notifyDataSetChanged();
    }

    public List<OrderInfoGroupBean> getList() {
        return mList;
    }

    private OrderListener mOrderListener;

    public void setOrderListener(OrderListener listener) {
        this.mOrderListener = listener;
    }

    public interface OrderListener {
        /**
         * 退订
         * @param order
         */
        void onClickSell(OrderInfoBean order);

        /**
         * 去订购
         * @param proCode
         */
        void onClickOrderMarket(String proCode);

        /**
         * 修改
         * @param order
         */
        void onClickChangeProfitLost(OrderInfoBean order);

        /**
         * 提货
         * @param order
         */
        void onClickGetGoods(OrderInfoBean order);

        /**
         * 提示
         * @param order
         */
        void onClickExplain(OrderInfoBean order);

        /**
         * 详情
         * @param order
         */
        void onClickDetail(OrderInfoBean order);
    }
}
